<?php

class EventController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/event';

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('hotevents','topevents','search','category','time','index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','delete','myevents'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
        $event = $this->loadModel($id);
		$event->view($id);
		if (isset($_POST['Event']))
		{
			$event->attributes=$_POST['Event'];
            $event->like($id);
            Yii::app()->user->setFlash('likeSubmitted',"You've liked this event.");
            /*
            if (isset($_POST['yt1']))
            {
                $event->unlike($id);
                Yii::app()->user->setFlash('likeSubmitted',"You've unliked this event.");
            }
            */
            $event->_view($id,2);
            $this->refresh();
		}
        $comment = $this->createComment ($event);
        $dataProvider = new CActiveDataProvider ('Comment', array (
            'criteria'=>array(
                'condition'=>'event_id='.$id,
                'order'=>'create_time DESC',
            ),
            'pagination'=>array (
                'pageSize'=>3,
            ),
        
        ));
		$this->render('view',array(
			'model'=>$event,
            'comment'=>$comment,
            'dataProvider'=>$dataProvider,
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Event;
		$model->setScenario('create');
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Event']))
		{
			$model->time = $_POST['hour'].':'.$_POST['min'].':00';
			$model->attributes=$_POST['Event'];
			if($model->save())
				if($this->createLike($model))
					$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);
		if (Yii::app()->user->id === $model->create_user_id) 
		{
			// Uncomment the following line if AJAX validation is needed
			// $this->performAjaxValidation($model);
			if(isset($_POST['Event']))
			{
				$model->attributes=$_POST['Event'];
				if($model->save())
				$this->redirect(array('view','id'=>$model->id));
			}
			$this->render('update',array(
				'model'=>$model,
		));
		}else
		{
			echo "ban khong co quyen update";
		}
		
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$model=$this->loadModel($id);
		if (Yii::app()->user->id === $model->create_user_id)
		{
			if(Yii::app()->request->isPostRequest)
			{
				// we only allow deletion via POST request
				$this->loadModel($id)->delete();

				// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
				if(!isset($_GET['ajax']))
					$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
			}
			else
				throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
		}
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		$dataProvider=new CActiveDataProvider('Event', array (
            'criteria'=>array(
                'order'=>'date DESC',
            ),
            'pagination'=>array(
                'pageSize'=>7,
            ),
        ));
		$this->render('index',array(
			'dataProvider'=>$dataProvider,
		));
	}
    
    public function actionTime ($time)
    {
        if ($time !== "today" AND $time !== "tomorrow" AND $time !== "thisweek" AND $time !== "thismonth") {}
        else {
        if ($time === "today"){ $_time = "date=UTC_DATE()";$time="ToDay";}
        elseif ($time === "tomorrow"){ $_time = "date=UTC_DATE()+1";$time="Tomorrow";}
        elseif ($time === "thisweek"){ $_time = "YEARWEEK(date)=YEARWEEK(UTC_DATE())";$time="This Week";}
        elseif ($time === "thismonth"){ $_time = "MONTH(date)=MONTH(UTC_DATE()) AND YEAR(date)=YEAR(UTC_DATE())";$time="This Month";}
        $dataProvider = new CActiveDataProvider ('Event', array (
            'criteria'=>array(
                'condition'=>$_time,
                'order'=>'date DESC',
            ),
            'pagination'=>array(
                'pageSize'=>5,
            ),
        ));
        
        $this->render('index',array('model'=>$time,'dataProvider'=>$dataProvider));
        }
    }
    
    public function actionCategory($type)
	{ 
	   $_model = Typeevent::model()->findByAttributes(array('name'=>$type));
		$dataProvider=new CActiveDataProvider('Event', array (
            'criteria'=> array(
                'condition'=>'id_type='.$_model->id_type,
                'order'=>'date DESC',
            ),
        
            'pagination'=>array(
                'pageSize'=>3,
            ),
        ));
		$this->render('index',array('model'=>$type,'dataProvider'=>$dataProvider,));
	}
	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Event('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Event']))
			$model->attributes=$_GET['Event'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Event::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='event-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
    
    protected function createComment ($event)
    {
        $comment = new Comment;
        $comment->event_id = $event->id;
        if (isset($_POST['Comment']))
        {
			if ($event->_view($event->id,2)===true)
			{
				$comment->attributes=$_POST['Comment'];
				if ($this->addComment($comment))
				{
					Yii::app()->user->setFlash('commentSubmitted',"Your comment has been added.");
					$this->refresh();
				}
			}
            
        }
        return $comment;
    }
    
    public function addComment ($comment)
    {
        return $comment->save();
    }
	
	public function actionSearch ()
	{
		$model = new Event('search');
		$model->unsetattributes();
		if (isset($_GET['Event']))
		{
			$model->attributes=$_GET['Event'];
			$this->render ('search', array('model'=>$model));
		}
	}
	
	public function createLike ($event)
	{
		$like = new Like;
		$like->event_id = $event->id;
		$like->view = 0;
		$like->like = 0;
		return $like->save();
	}
	
	public function actionTopevents()
	{
		$dataProvider = new CActiveDataProvider('Event', array(
			'criteria'=>array(
				'condition'=>'t.id=likes.event_id',
				'with'=>array(
					'likes'=>array(
						'order'=>'likes.like DESC',
					),
				),
			),
			'pagination'=>array (
                'pageSize'=>5,
            ),
		));
		$this->render('topevents', array('dataProvider'=>$dataProvider));
	}
	public function actionHotevents()
	{
		$dataProvider = new CActiveDataProvider('Event', array(
			'criteria'=>array(
				'condition'=>'t.id=likes.event_id',
				'with'=>array(
					'likes'=>array(
						'order'=>'likes.view DESC',
					),
				),
			),
			'pagination'=>array (
                'pageSize'=>5,
            ),
		));
		$this->render('hotevents', array('dataProvider'=>$dataProvider));
	}
    public function actionMyevents()
	{
		$dataProvider = new CActiveDataProvider('Event', array(
			'criteria'=>array(
				'condition'=>'create_user_id='.Yii::app()->user->id,
			),
			'pagination'=>array (
                'pageSize'=>5,
            ),
		));
		$this->render('index', array('model'=>'My Event(s)','dataProvider'=>$dataProvider));
	}
}
